package com.itheima.controller;

import com.itheima.common.R;
import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.savePath}")
    private String basePath;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        //解决同名文件覆盖问题
        String uuid = UUID.randomUUID().toString();
        //获取上传文件的名称
        String originalFilename = file.getOriginalFilename();
        //获取后缀名
        String extension = FilenameUtils.getExtension(originalFilename);
        //拼接文件保存名称
        String saveName = uuid+"."+extension;
        //将文件保存到指定位置
        file.transferTo(new File(basePath + saveName));
        //响应给前端
        return R.success(saveName);
    }

    @GetMapping("/download")
    public R download(String name, HttpServletResponse response) throws IOException {

        try (FileInputStream fileInputStream = new FileInputStream(new File(basePath + name))) {
            //通过io流的工具类读取文件
            IOUtils.copy(fileInputStream, response.getOutputStream());
        }
        //关流
        return R.success("保存成功");
    }
}
